package com.arcvideo.acsconnect.ui.presenter;

import android.content.Context;
import android.text.TextUtils;

import com.arcvideo.acsconnect.app.AccessAction;
import com.arcvideo.acsconnect.app.AcsConnectApplication;
import com.arcvideo.acsconnect.rest.model.Account;
import com.arcvideo.acsconnect.rest.model.ResultBean;
import com.arcvideo.acsconnect.rest.model.UpgradeResultBean;
import com.arcvideo.acsconnect.rest.model.UserBean;
import com.arcvideo.acsconnect.rest.service.AppService;
import com.arcvideo.acsconnect.ui.view.MainView;
import com.framework.core.ValidateParam;
import com.framework.core.bean.RestError;
import com.framework.core.mvp.BasePresenter;
import com.framework.core.mvp.IObserver;
import com.framework.core.utils.AppUtil;

import java.util.List;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * @author shenmengchao
 * @version 1.0.0
 * @date 2017/11/16
 * @description
 */

public class MainPresenter extends BasePresenter<MainView> {

    AppService mAppService;

    public MainPresenter() {
        super();
        mAppService = mRetrofit.create(AppService.class);
    }

    public void getAccountsByStbId(Context context) {
        mAppService.getAccountsByStbId(
                AccessAction.GET_ACCOUNTS_BY_STBID,
                System.currentTimeMillis() + "",
                getStbId(context)
        ).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new IObserver<ResultBean<List<UserBean>>>(this, true) {
                    @Override
                    public boolean onFailed(RestError restError) {
                        return false;
                    }

                    @Override
                    public void onNext(ResultBean<List<UserBean>> listResultBean) {
                        List<UserBean> list = listResultBean.getResult();
                        for (int i = 0; i < list.size(); i++) {
                            if (list.get(i).isOnline()) {
                                AcsConnectApplication.sCurrentUserIndex = i;
                                break;
                            }
                        }
                        AcsConnectApplication.sUserList = list;
                        getMvpView().onGetAccountsByStbIdSuccess(list);
                    }
                });
    }

    public void login(String account, String password) {
        mAppService.login(
                AccessAction.LOGIN,
                account,
                password
        ).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new IObserver<ResultBean<UserBean>>(this, true) {
                    @Override
                    public boolean onFailed(RestError restError) {
                        return false;
                    }

                    @Override
                    public void onNext(ResultBean<UserBean> userBeanResultBean) {
                        UserBean userBeanDefault = userBeanResultBean.getResult();
                        ValidateParam.ACCESS_KEY = userBeanDefault.getAccessKey();
                        ValidateParam.SECRET = userBeanDefault.getAccessSecret();
                        getMvpView().onLoginSuccess(userBeanDefault);
                    }
                });
    }

//    public void logout() {
//        mAppService.logout(AccessAction.LOGOUT, System.currentTimeMillis() + "")
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new IObserver<ResultBean<UserBean>>(this) {
//                    @Override
//                    public boolean onFailed(RestError restError) {
//                        return false;
//                    }
//
//                    @Override
//                    public void onNext(ResultBean<UserBean> userBeanResultBean) {
//                        ToastUtil.showToast("登出成功");
//                    }
//                });
//    }

    public void logoutAndLoginOther(final int index) {
        Observable<ResultBean<UserBean>> logout =
                mAppService.logout(AccessAction.LOGOUT, System.currentTimeMillis() + "");
        UserBean userBean = AcsConnectApplication.sUserList.get(index);
        final Observable<ResultBean<UserBean>> loginOther =
                mAppService.login(AccessAction.LOGIN, userBean.getAccount(), userBean.getPassword());


        logout.subscribeOn(Schedulers.io())
                .flatMap(new Func1<ResultBean<UserBean>, Observable<ResultBean<UserBean>>>() {
                    @Override
                    public Observable<ResultBean<UserBean>> call(ResultBean<UserBean> userBeanResultBean) {
                        return loginOther;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new IObserver<ResultBean<UserBean>>(this, true) {
                    @Override
                    public boolean onFailed(RestError restError) {
                        return false;
                    }

                    @Override
                    public void onNext(ResultBean<UserBean> userBeanResultBean) {
                        UserBean userBean = userBeanResultBean.getResult();
                        ValidateParam.ACCESS_KEY = userBean.getAccessKey();
                        ValidateParam.SECRET = userBean.getAccessSecret();
                        AcsConnectApplication.sCurrentUserIndex = index;
                        getMvpView().onLogoutAndLoginOtherSuccess(userBean);
                    }
                });
    }

    public void getNurseAccounts() {
        mAppService.getAccountsByPage(
                AccessAction.GET_ACCOUNTS_BY_PAGE,
                System.currentTimeMillis() + "",
                "",
                "3,5"
        ).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new IObserver<ResultBean<List<Account>>>(this, true) {
                    @Override
                    public boolean onFailed(RestError restError) {
                        return false;
                    }

                    @Override
                    public void onNext(ResultBean<List<Account>> userBeanResultBean) {
                        AcsConnectApplication.sNurseList = userBeanResultBean.getResult();
                    }
                });
    }

    public void checkNewVersion(Context context) {
        mAppService.checkNewVersion(AccessAction.CHECK_NEW_VERSION,
                System.currentTimeMillis() + "",
                AppUtil.getVersionName(context))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new IObserver<ResultBean<UpgradeResultBean>>(this) {
                    @Override
                    public boolean onFailed(RestError restError) {
                        return false;
                    }

                    @Override
                    public void onNext(ResultBean<UpgradeResultBean> resultBean) {
                        UpgradeResultBean upgradeResultBean = resultBean.getResult();
                        upgradeResultBean.setNeedUpgrade(0 == resultBean.getCode());
                        getMvpView().onCheckNewVersionSuccess(upgradeResultBean);
                    }
                });
    }

    private String getStbId(Context context) {
        String stbId = AppUtil.getStbId(context);
        if (TextUtils.isEmpty(stbId) || stbId.equals("unknown")) {
            return "testStbId";
        }
        return stbId;
    }
}
